#-*- coding: utf-8 -*-

#This file is part of pyLot library.
#
# pyLot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyLot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pyLot.  If not, see <http://www.gnu.org/licenses/>.

__author__ = u'Pierre Puiseux, Guillaume Baty'
__copyright__ = u"Copyright 2011-2012 (C) andheo, Université de Pau et des Pays de l'Adour"
__credits__ = [u'Pierre Puiseux', u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"

"""
Functions to eval python expressions.
Todo: use ast
"""

__all__ = [
  'eval_literal',
  'eval_type',
  'eval_value_expr'
  ]

import ast
import re
from ast import literal_eval
from _pylot.data.regexpr import match, re_anum

eval_literal = literal_eval

# <op> <value> <op>
re_op = '((<|>|=|!))*\s*value\s*((<|>|=|!))*'

co_expr = re.compile('(%s)?\s*(%s)\s*(%s)?' % (re_anum, re_op, re_anum))

def eval_value_expr(s, value):
  u"""
  eval numerical value.
  Currently, only int and floats are supported
  """
  # todo, improve using ast
  if match(co_expr, s):
    return eval(s, {}, dict(value=value))
  else :
    raise ValueError

def eval_type(s, allowed_types=[]):
  u"""
  eval type "s" if type is in allowed_types.
  
  >>> eval_type('int', allowed_types=[int, float])
  <type 'int'>
  >>> eval_type('int', allowed_types=[str, unicode])
  Traceback (most recent call last):
  ...
  NameError: int
  """
  # todo, improve using ast
  type_names = {}
  for t in allowed_types:
    type_names[t.__name__] = t
  s = s.strip()
  if not s :
    return None
  elif s in type_names :
    return eval(s, {}, type_names)
  else :
    raise NameError(s)


if __name__ == '__main__' :
  pass
